using Tanks.Step3;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using Random = Unity.Mathematics.Random;

namespace Tanks.Step8
{
    [UpdateInGroup(typeof(LateSimulationSystemGroup))]
    public partial struct CameraSystem : ISystem
    {
        Entity mTarget;
        Random mRandom;

        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Execute.Camera>();
            mRandom = new Random(123);
        }

        //方法内部使用了托管对象时不可使用 BurstCompile
        //[BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            if (mTarget == Entity.Null || Input.GetKeyDown(KeyCode.Space))
            {
                var tankQuery = SystemAPI.QueryBuilder().WithAll<Tank>().Build();
                var tanks = tankQuery.ToEntityArray(Allocator.Temp);
                if (tanks.Length == 0) return;
                mTarget = tanks[mRandom.NextInt(tanks.Length)];
            }

            var cameraTrans = CameraSingleton.Instance.transform;
            var tankTrans = SystemAPI.GetComponent<LocalToWorld>(mTarget);
            cameraTrans.position = tankTrans.Position - 10f * tankTrans.Forward + new float3(0, 5f, 0);
            cameraTrans.LookAt(tankTrans.Position);
        }
    }
}